<template>
  <div class="w-286px h-full mb-[0!important] !overflow-y-auto bg-#F5F9FF rounded-tr-16px">
    <view class="flex items-center justify-center w-full sticky-mode-switch">
      <el-radio-group v-model="generateMode">
        <el-radio-button value="desc" :border="true"> 描述模式 </el-radio-button>
        <el-radio-button value="lyric" :border="true"> 歌词模式 </el-radio-button>
      </el-radio-group>
    </view>
    <Title v-if="generateMode === 'desc'" title="纯音乐" class="pl-10px">
      <el-switch class="!h-auto" v-model="makeInstrumental" />
    </Title>
    <!-- 描述模式/歌词模式 切换 -->
    <component :is="curComponent" :type="generateMode" ref="modeRef" />
    <div class="w-full flex justify-center mb-20px">
      <el-button
        class="w-120px h-36px !rounded-6px text-16px create-button"
        type="primary"
        @click="handleGenerateMusic"
      >
        创作音乐
      </el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { MusicApi } from '@/api/ai/music'
import desc from './desc.vue'
import lyric from './lyric.vue'
import Title from '../title/index.vue'
const message = useMessage() // 消息弹窗
defineOptions({ name: 'Index' })

const emits = defineEmits(['onDrawComplete'])

const generateMode = ref('desc')
const curComponent = computed(() => {
  return generateMode.value === 'desc' && makeInstrumental.value ? desc : lyric
})
const makeInstrumental = ref(false) // 是否生成纯音乐
const modeRef = ref<
  Nullable<{
    formData: Recordable
    validate: () => Promise<any>
    setFormData: (data: Recordable) => void
  }>
>(null)
// 定义属性
const drawIn = ref<boolean>(false) // 生成中
const formData = ref<Recordable>({ title: '', prompt: '' })
watch(
  () => {
    return {
      title: unref(modeRef)?.formData?.title || '',
      prompt: unref(modeRef)?.formData?.prompt || ''
    }
  },
  (val) => {
    if (val.title || val.prompt) {
      formData.value = val
    }
  }
)
watch(curComponent, () => {
  nextTick(() => {
    if (formData.value.title || formData.value.prompt) {
      unref(modeRef)?.setFormData?.(formData.value)
    }
  })
})
/** 视频生成 */
const handleGenerateMusic = async () => {
  if (drawIn.value) {
    message.warning('添加音乐任务中，请稍后再试')
    return
  }
  await unref(modeRef)?.validate?.()
  // 二次确认
  await message.confirm(`确认生成内容?`)
  try {
    // 加载中
    drawIn.value = true
    await MusicApi.generateMusic({
      ...unref(modeRef)?.formData,
      makeInstrumental: makeInstrumental.value,
      generateMode: generateMode.value === 'desc' ? 1 : 2
    })
    message.success('已添加至音乐任务')
  } finally {
    // 回调
    emits('onDrawComplete')
    // 加载结束
    drawIn.value = false
  }
}
</script>

<style scoped>
.sticky-mode-switch {
  position: sticky;
  top: 0;
  z-index: 10;
  padding-top: 8px;
  padding-bottom: 8px;
  background: #f5f9ff;
}

.create-button {
  background: linear-gradient(90deg, #8a9bff 0%, #bc9eff 100%);
  border: 0 !important;
  border-radius: 6px;
}
</style>
